package com.heima.article.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.consatnts.article.ArticleConstants;
import com.heima.common.consatnts.message.NewsUpOrDownConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleHomeDTO;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    GeneratePageService generatePageService;
@Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    @GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 100000)
    public void publishArticle(Integer newsId) {
        //1.查询并检查自媒体文章  wmNews
        WmNews wmNews = getWmNews(newsId);
        //2.封装ApArticle
        ApArticle apArticle = getApArticle(wmNews);
        //3.保存或修改 article信息
        saveOrUpdateArticle(apArticle);
        //4.保存关联配置和内容信息
        saveConfigAndContent(wmNews, apArticle);
        //5.TODO 文章页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(), apArticle);
        //6. 更新 wmNews 状态 改为9 并设置articleId
        updateWmNewsStatus(newsId, wmNews, apArticle);
        //7.TODO 通知es索引库添加文章索引
        rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE,apArticle.getId());
        log.info("文章发布成功，并发送索引库更新通知   文章id: {}",apArticle.getId());
    }

    @Autowired
    private ApArticleMapper apArticleMapper;
    @Value("${file.oss.web-site}")
    String webSite;

    @Value("${file.minio.readPath}")
    String readPath;

    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        // 1. 参数校验
        // 分页
        Integer size = dto.getSize();
        if(size==null||size<=0){
            dto.setSize(10);
        }
        // 频道
        if(StringUtils.isBlank(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        // 时间
        if(dto.getMaxBehotTime() == null){
            dto.setMaxBehotTime(new Date());
        }
        if(dto.getMinBehotTime() == null){
            dto.setMinBehotTime(new Date());
        }
        // type类型 必须为0 或 1
        if (!ArticleConstants.LOADTYPE_LOAD_MORE.equals(loadtype)&&!ArticleConstants.LOADTYPE_LOAD_NEW.equals(loadtype)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        // 2. 执行查询
        List<ApArticle> articleList = apArticleMapper.loadArticleList(dto, loadtype);
        for (ApArticle article : articleList) {
            // 获取文章封面字段
            String images = article.getImages();
            if (StringUtils.isNotBlank(images)) {
                // 将封面按照,号切割   生成流
                images = Arrays.stream(images.split(","))
                        // 每一个路径添加前缀
                        .map(url -> webSite + url)
                        // 将加了前缀的路径  拼接成字符串
                        .collect(Collectors.joining(","));
                article.setImages(images);
            }
            // 拼接 静态页面的前缀路径
            article.setStaticUrl(readPath + article.getStaticUrl());

        }
        // 3. 返回结果
        return ResponseResult.okResult(articleList);
    }

    /**
     * 根据参数加载文章列表
     * @param loadtypeLoadMore 0为加载更多  1为加载最新
     * @param dto
     * @param firstPage 是否为首页  true 首页
     * @return
     */
    @Autowired
    StringRedisTemplate redisTemplate;
    @Override
    public ResponseResult load2(Short loadtypeLoadMore, ArticleHomeDTO dto, boolean firstPage) {
       if(firstPage){
           //从缓冲中 查询
           String hotArticleJson = redisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
           if(StringUtils.isNotBlank(hotArticleJson)){
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(hotArticleJson, HotArticleVo.class);
               for (HotArticleVo articleVo : hotArticleVoList) {
                   String images = articleVo.getImages();
                   //给封面拼接访问前缀
                   if(StringUtils.isNotBlank(images)){
                       images= Arrays.stream(images.split(",")).map(url->webSite+url).collect(Collectors.joining(","));
                       articleVo.setImages(images);
                   }
                   //拼接静态页面路径
                   articleVo.setStaticUrl(readPath+articleVo.getStaticUrl());
               }
               return ResponseResult.okResult(hotArticleVoList);
           }
       }
        return load(loadtypeLoadMore,dto);
    }

    /**
     * 更改wmNews 信息
     *
     * @param newsId
     * @param wmNews
     * @param apArticle
     */
    private void updateWmNewsStatus(Integer newsId, WmNews wmNews, ApArticle apArticle) {
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        wmNews.setArticleId(apArticle.getId());
        ResponseResult responseResult = wemediaFeign.updateWmNews(wmNews);
        if (!responseResult.checkCode()) {
            log.error("文章发布失败 远程调用失败");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用失败");
        }
    }

    /**
     * 保存关联配置和内容信息
     *
     * @param wmNews
     * @param apArticle
     */
    private void saveConfigAndContent(WmNews wmNews, ApArticle apArticle) {
        //添加配置信息
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDelete(false);
        apArticleConfigMapper.insert(apArticleConfig);
        //添加内容信息
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        apArticleContentMapper.insert(apArticleContent);
    }

    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    ApArticleContentMapper apArticleContentMapper;

    /**
     * 保存或修改 article信息
     *
     * @param apArticle
     */
    private void saveOrUpdateArticle(ApArticle apArticle) {
        if (apArticle.getId() == null) {
            //保存
            apArticle.setCollection(0); //收藏数
            //点赞数
            apArticle.setLikes(0);
            //评论数
            apArticle.setComment(0);
            //阅读数
            apArticle.setViews(0);
            save(apArticle);
        } else {
            //1修改文章 有关联 2删除之前关联的配置信息 3内容信息
            ApArticle article = this.getById(apArticle.getId());
            if (article == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "关联的文章不存在");
            }
            //更改ApArticle 的信息
            updateById(apArticle);
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, apArticle.getId()));
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, apArticle.getAuthorId()));

        }

    }

    @Autowired
    AdminFeign adminFeign;

    @Autowired
    AuthorMapper authorMapper;

    /**
     * 封装ApArticle
     *
     * @param wmNews
     * @return
     */
    private ApArticle getApArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(wmNews, apArticle);
        apArticle.setId(wmNews.getArticleId());
        apArticle.setFlag((byte) 0); //普通文章
        apArticle.setLayout(wmNews.getType()); //布局
        //远程查询频道信息
        ResponseResult<AdChannel> channelResult = adminFeign.findOne(wmNews.getChannelId());
        if (!channelResult.checkCode()) {
            log.error("文章发布失败 远程调用查询频道出现异常 ，不予发布， 文章id :{} 频道id:{}", wmNews.getId(), wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        AdChannel channel = channelResult.getData();
        if (channel == null) {
            log.error("文章发布失败  未查到相关频道");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "问查询到相关频道");
        }
        apArticle.setChannelName(channel.getName());
        //设置作者信息
        ApAuthor apAuthor = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        if (apAuthor == null) {
            log.error("文章发布失败 未查询到相关作者信息");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            apArticle.setAuthorId(Long.valueOf(apAuthor.getId()));
        }
        apArticle.setAuthorId(Long.valueOf(apAuthor.getId()));
        apArticle.setAuthorName(apAuthor.getName());

        return apArticle;
    }

    @Autowired
    WemediaFeign wemediaFeign;

    /**
     * 查询自媒体文章
     *
     * @param newsId
     * @return
     */
    private WmNews getWmNews(Integer newsId) {
        ResponseResult<WmNews> newsResponseResult = wemediaFeign.findWmNewsById(newsId);
        //远程调用需要先盘判断状态
        if (!newsResponseResult.checkCode()) {
            log.error("文章发布失败 远程调用自媒体文章接口失败 文章id{} ", newsId);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        WmNews wmNews = newsResponseResult.getData();
        //判断是否有改文章
        if (wmNews == null) {
            log.error("该id不存在 id :{}", newsId);
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "该文章不存在");
        }
        //判断状态是否为 4 或8 ，如果不是不处理
        if (WmNews.Status.ADMIN_SUCCESS.getCode() != wmNews.getStatus() && WmNews.Status.SUCCESS.getCode() != wmNews.getStatus()) {
            log.error("文章发布失败 文章状态不为4 或8 不予发布 ，文章id：{}", newsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "自媒体文章状态错误");
        }
        return wmNews;
    }
}